package com.eleadmin.store.biz.impl;

import com.eleadmin.damon.utils.constant.UserConstant;
import com.eleadmin.damon.utils.results.BaseDao;
import com.eleadmin.damon.utils.results.PageResult2;
import com.eleadmin.damon.utils.utils.DateUtil;
import com.eleadmin.damon.utils.utils.Utils;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.store.biz.SellBiz;
import com.eleadmin.store.entity.Sell;
import com.eleadmin.common.core.web.JsonResult;
import com.eleadmin.store.result.PriceResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * 数据层实现类
 *
 * @author : Doman
 * @version ：1.0
 * @date : 2024-03-07 14:12:18
 */
@Repository
public class SellBizImpl extends BaseDao implements SellBiz {

    @Override
    public JsonResult list(PageResult2<T> page, Sell sell, User loginUser) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<Sell> rm = new BeanPropertyRowMapper<Sell>(Sell.class);
        StringBuffer sql = new StringBuffer("select s.id,s.organization_id,s.code");
        sql.append(",s.supplier,s.sellTime,s.unpaid,s.state");
        sql.append(",s.invoice,s.total,s.remark,s.create_time");
        sql.append(",s.create_user,s.update_time,s.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName,suser2.nickname updateName ");
        sql.append(" from we_sell s ");
        sql.append(" inner join sys_user suser on suser.user_id=s.create_user ");
        sql.append(" left join sys_user suser2 on suser2.user_id=s.update_user ");
        if(Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification()) || Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" inner join we_sell_son ss on ss.sellId=s.id ");
            }
        }
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=s.organization_id and sogzn.deleted=0 ");
        sql.append(" where s.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and s.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification())) {
                sql.append(" and instr(ss.specification,:specification)>0 ");
                map.put("specification", sell.getSpecification());
            }
            if (Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" and instr(ss.productName,:productName)>0 ");
                map.put("productName", sell.getProductname());
            }
            if (Utils.isNotEmpty(sell.getKeywords())) {
                sql.append(" and instr(s.code,:keywords)>0 ");
                map.put("keywords", sell.getKeywords());
            }
            if (Utils.isNotEmpty(sell.getSupplier())) {
                sql.append(" and instr(s.supplier,:supplier)>0");
                map.put("supplier", sell.getSupplier());
            }
            if(Utils.isNotEmpty(sell.getDate1())){
                sql.append(" and s.sellTime>=:date1 ");
                map.put("date1", sell.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(sell.getDate2())){
                sql.append(" and s.sellTime<=:date2 ");
                map.put("date2", sell.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(sell.getState())) {
                sql.append(" and s.state=:state");
                map.put("state", sell.getState());
            }
            if (Utils.isNotEmpty(sell.getInvoice())) {
                sql.append(" and s.invoice=:invoice");
                map.put("invoice", sell.getInvoice());
            }
            if (Utils.isNotEmpty(sell.getSort()) && Utils.isNotEmpty(sell.getOrder())) {
                sql.append(" order by s." + sell.getSort() + " " + sell.getOrder());
            } else {
                sql.append(" order by s.create_time desc");
            }
        }
        return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
    }

    @Override
    public PriceResult sellNums(Sell sell, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<PriceResult> rm = new BeanPropertyRowMapper<PriceResult>(PriceResult.class);
        StringBuffer sql = new StringBuffer("select  ");
        sql.append(" ROUND(IFNULL(sum(s.unpaid),0),2) unpaid ");
        sql.append(" ,ROUND(IFNULL(sum(s.total),0),2) total ");
        sql.append(" from we_sell s ");
        if(Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification()) || Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" inner join we_sell_son ss on ss.sellId=s.id ");
            }
        }
        sql.append(" where s.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and s.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification())) {
                sql.append(" and instr(ss.specification,:specification)>0 ");
                map.put("specification", sell.getSpecification());
            }
            if (Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" and instr(ss.productName,:productName)>0 ");
                map.put("productName", sell.getProductname());
            }
            if (Utils.isNotEmpty(sell.getKeywords())) {
                sql.append(" and instr(s.code,:keywords)>0 ");
                map.put("keywords", sell.getKeywords());
            }
            if (Utils.isNotEmpty(sell.getSupplier())) {
                sql.append(" and instr(s.supplier,:supplier)>0");
                map.put("supplier", sell.getSupplier());
            }
            if(Utils.isNotEmpty(sell.getDate1())){
                sql.append(" and s.sellTime>=:date1 ");
                map.put("date1", sell.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(sell.getDate2())){
                sql.append(" and s.sellTime<=:date2 ");
                map.put("date2", sell.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(sell.getState())) {
                sql.append(" and s.state=:state");
                map.put("state", sell.getState());
            }
            if (Utils.isNotEmpty(sell.getInvoice())) {
                sql.append(" and s.invoice=:invoice");
                map.put("invoice", sell.getInvoice());
            }
            if (Utils.isNotEmpty(sell.getSort()) && Utils.isNotEmpty(sell.getOrder())) {
                sql.append(" order by s." + sell.getSort() + " " + sell.getOrder());
            } else {
                sql.append(" order by s.create_time desc");
            }
        }
        getMapParameter(sql, map);
        List<PriceResult> priceResults = jdbcTemplate.query(sql.toString(), map, rm);
        return Utils.isNotEmpty(priceResults)?priceResults.get(0): null;
    }

    @Override
    public List<Sell> list(Sell sell, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<Sell> rm = new BeanPropertyRowMapper<Sell>(Sell.class);
        StringBuffer sql = new StringBuffer("select s.id,s.organization_id,s.code");
        sql.append(",s.supplier,s.sellTime,s.unpaid,s.state");
        sql.append(",s.invoice,s.total,s.remark,s.create_time");
        sql.append(",s.create_user,s.update_time,s.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from we_sell s ");
        sql.append(" inner join sys_user suser on suser.user_id=s.create_user ");
        if(Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification()) || Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" inner join we_sell_son ss on ss.sellId=s.id ");
            }
        }
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=s.organization_id and sogzn.deleted=0 ");
        sql.append(" where s.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and s.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(sell)) {
            if (Utils.isNotEmpty(sell.getSpecification())) {
                sql.append(" and instr(ss.specification,:specification)>0 ");
                map.put("specification", sell.getSpecification());
            }
            if (Utils.isNotEmpty(sell.getProductname())) {
                sql.append(" and instr(ss.productName,:productName)>0 ");
                map.put("productName", sell.getProductname());
            }
            if (Utils.isNotEmpty(sell.getKeywords())) {
                sql.append(" and instr(s.code,:keywords)>0 ");
                map.put("keywords", sell.getKeywords());
            }
            if (Utils.isNotEmpty(sell.getSupplier())) {
                sql.append(" and instr(s.supplier,:supplier)>0");
                map.put("supplier", sell.getSupplier());
            }
            if(Utils.isNotEmpty(sell.getDate1())){
                sql.append(" and s.sellTime>=:date1 ");
                map.put("date1", sell.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(sell.getDate2())){
                sql.append(" and s.sellTime<=:date2 ");
                map.put("date2", sell.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(sell.getState())) {
                sql.append(" and s.state=:state");
                map.put("state", sell.getState());
            }
            if (Utils.isNotEmpty(sell.getInvoice())) {
                sql.append(" and s.invoice=:invoice");
                map.put("invoice", sell.getInvoice());
            }
            if (Utils.isNotEmpty(sell.getSort()) && Utils.isNotEmpty(sell.getOrder())) {
                sql.append(" order by s." + sell.getSort() + " " + sell.getOrder());
            } else {
                sql.append(" order by s.create_time desc");
            }
        }
        getMapParameter(sql, map);
        return jdbcTemplate.query(sql.toString(), map, rm);
    }

    @Override
    public Sell getById(String id) {
        RowMapper<Sell> rm = new BeanPropertyRowMapper<Sell>(Sell.class);
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("select s.id,s.organization_id,s.code");
        sql.append(",s.supplier,s.sellTime,s.unpaid,s.state");
        sql.append(",s.invoice,s.total,s.remark,s.create_time");
        sql.append(",s.create_user,s.update_time,s.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from we_sell s ");
        sql.append(" inner join sys_user suser on suser.user_id=s.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=s.organization_id and sogzn.deleted=0 ");
        sql.append(" where s.deleted=0 and s.id=:id ");
        map.put("id", id);
        getMapParameter(sql, map);
        try {
            return jdbcTemplate.queryForObject(sql.toString(), map, rm);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Integer save(Sell sell, User loginUser) {
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        KeyHolder keyHolder = new GeneratedKeyHolder();
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("insert into we_sell (");
        sql.append("organization_id,code,supplier,sellTime");
        sql.append(",unpaid,state,invoice,total");
        sql.append(",remark,create_user,create_time) values ( ");
        sql.append(":organization_id,:code,:supplier,:sellTime");
        sql.append(",:unpaid,:state,:invoice,:total");
        sql.append(",:remark,:create_user,now())");
        map.put("organization_id", loginUser.getOrganizationId() + "");
        map.put("code", sell.getCode());
        map.put("supplier", sell.getSupplier());
        map.put("sellTime", sell.getSelltime());
        map.put("unpaid", sell.getUnpaid());
        map.put("state", sell.getState());
        map.put("invoice", sell.getInvoice());
        map.put("total", sell.getTotal());
        map.put("remark", sell.getRemark());
        map.put("create_user", loginUser.getUserId() + "");
        getMapParameter(sql, map);
        int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
            @Override
            public boolean hasValue(String paramName) {
                return map.containsKey(paramName);
            }

            @Override
            public Object getValue(String paramName) throws IllegalArgumentException {
                return map.get(paramName);
            }
        }, generatedKeyHolder);

        Integer id = generatedKeyHolder.getKey().intValue();
        return id;
    }

    @Override
    public boolean update(Sell sell, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_sell set ");
        sql.append("code=:code,supplier=:supplier,sellTime=:sellTime ");
        sql.append(",unpaid=:unpaid,state=:state,invoice=:invoice ");
        sql.append(",total=:total,remark=:remark,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("code", sell.getCode());
        map.put("supplier", sell.getSupplier());
        map.put("sellTime", sell.getSelltime());
        map.put("unpaid", sell.getUnpaid());
        map.put("state", sell.getState());
        map.put("invoice", sell.getInvoice());
        map.put("total", sell.getTotal());
        map.put("remark", sell.getRemark());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", sell.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean updateTableState(Sell sell, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_sell set ");
        sql.append("state=:state,invoice=:invoice,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("state", sell.getState());
        map.put("invoice", sell.getInvoice());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", sell.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean updateTotal(Sell sell, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_sell set ");
        sql.append("total=:total,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("total", sell.getTotal());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", sell.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean remove(String id, User loginUser) {
        int count = 0;
        Map<String, String> map = null;
        if (id.length() > 0) {
            for (String id1 : id.split(",")) {
                map = new HashMap<String, String>();
                if (id1 == null || id1.equals("")) {
                    break;
                }
                StringBuffer sql = new StringBuffer("update we_sell set deleted=1" +
                        ",update_user=:update_user, update_time=now() "
                        + " where id =:id ");
                map.put("update_user", loginUser.getUserId() + "");
                map.put("id", id1);
                getMapParameter(sql, map);
                count = jdbcTemplate.update(sql.toString(), map);
            }
        }
        return count > 0;
    }
}
